package com.liu.algorithm01;

public class BinarySearch02 {
    public static void main(String[] args) {
        int[] arr = {8, 11, 14, 19, 20, 27, 29, 38};
        int index = search(arr, 19);
        System.out.println("Values is:" + index);
        int indexUpdate = searchUpdate(arr,19);
        System.out.println("Values is:" + indexUpdate);
        int indexBalance = searchBalance(arr,19);
        System.out.println("Values is:" + indexBalance);
    }
    // 平衡版
    private static int searchBalance(int[] a,int target){
        int count = 0;
        int i = 0, j = a.length;
        while (1 + i < j){
            int m = (i + j) >>> 1;
            if (target < a[m]){
                j = m;
            }else {
                i = m;
            }
        }
        return (a[i] == target) ? i : -1;
    }
    // 改动版
    private static int searchUpdate(int[] a,int target){
        int i = 0, j = a.length;
        while (i < j){
            int m = (i + j) >>> 1;
            if (target < a[m]){
                j = m;
            }else if (target > a[m]){
                i = m + 1;
            }else {
                return m;
            }
        }
        return -1;
    }
    // 基础版
    private static int search(int[] a, int target) {
        int i = 0, j = a.length - 1;
        while (i <= j) {
            int m = (i + j) >>> 1;
            if (target < a[m]) {
                j = m - 1;
            } else if (target > a[m]) {
                i = m + 1;
            } else {
                return m;
            }
        }
        return -1;
    }
}
